package com.cilico.shopcart;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cilico.R;
import com.cilico.components.Alert;
import com.cilico.components.Component;
import com.cilico.components.CssStyle;
import com.cilico.utils.PackageManagerAndroid;
import com.cilico.utils.Utils;
import com.cilico.view.BaseView;
import com.cilico.view.FormLayout;
import com.cilico.waterfall.ItemBase;
import com.cilico.waterfall.ItemMeal;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * 已购买列表
 * @author lvxiangan
 *
 */
public class ShopCartList extends LinearLayout implements Component {

	/** 上下文 */
	BaseView bv_;
	/** 控件名称 */
	public String attrName_;
	/** 控件值,json格式 */
	public String attrValue_;
	/** 显示数据, 用于每一个item的内容显示 */
	public String showValue_;
	/** 详细数据,一个item对应一个json段，代表当前item详细信息,相邻的item通过@号拼接，形式：json@json@json */
	public String realValue_;
	/** 控件宽度 */
	public int width_;
	/** 控件高度 */
	public int height_;
	/** 滑动列表 */
	private ListView listView_;
	/** 价格总计视图 */
	private TextView totalView_;
	/** 价格总计 */
	float sum_ = 0;
	/** 用于显示的items数据 */
	public ArrayList<ShopCartInfo> showDatas = new ArrayList<ShopCartInfo>();
	/** showDatas的各个item的实际数据 */
	public ArrayList<ItemBase> realDatas = new ArrayList<ItemBase>();
	/** 用来处理菜品列表删除后条数为0的情况 */
    private Handler handler;
    /** css样式 */
    public CssStyle cssStyle_;
    /** 保存份数列表 */
    public static HashMap<String, String> amountList = new HashMap<String, String>();
	
	public ShopCartList(BaseView bv, String name) {
		super(bv);
		bv_ = bv;
		attrName_ = name;
		initDatas();
		attrValue_ = toJsonString(realDatas);
		BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, attrValue_);
		
        // 初始化Handler,用来处理消息
        handler = new Handler() {
            public void handleMessage(Message message) {
                Bundle data = message.getData();
                switch (message.what) {
                case 1:
                    boolean isEmpty = data.getBoolean("isEmpty");
                    if (isEmpty) {
                    	ShopCartList.this.removeAllViews();
                    	TextView emptyView = new TextView(bv_);
                    	emptyView.setText("购物车暂无内容");
                    	addView(emptyView);
                    	postInvalidate();
                    }
                    break;
                }
            }
        };

		View options = (View) bv_.getLayoutInflater().inflate(R.layout.shopcart_local_layout, null);
        listView_ = (ListView) options.findViewById(R.id.shopcart_list);
        totalView_ = (TextView) options.findViewById(R.id.shopcart_total);
        totalView_.setText("合计：¥ " + sum_ + " 元");

        // 设置自定义Adapter
        ListAdapter adapter = new ListAdapter(bv_);
        listView_.setAdapter(adapter);
        addView(options);
	}

	private void caculateHeight() {
		if (realDatas.size() == 1) {
			height_ = Utils.screenHeight_ / 4;
		} else if (realDatas.size() == 2) {
			height_ = Utils.screenHeight_ / 3;
		} else if (realDatas.size() == 3) {
			height_ = Utils.screenHeight_ / 2;
		} else {
			height_ = Utils.screenHeight_ * 2 / 3;
		}
	}

	/**
     * 初始化填充Adapter所用List数据
     * 
     */
    private void initDatas() {
    	String showStr = null;
    	String realStr = null;
    	StringBuffer showBuf = new StringBuffer();
    	StringBuffer realBuf = new StringBuffer();
		if (ShopCart.order.size() > 0) {
			Iterator iter = ShopCart.order.entrySet().iterator();
			ShopCartInfo cartInfo;
			List <ItemBase> ls;
			String cachedAmount;
			while (iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
				String key = (String) entry.getKey();
				ItemMeal data = (ItemMeal) entry.getValue();
				
				cachedAmount = amountList.get(data.getId());
				if (TextUtils.isEmpty(cachedAmount)) {
					cachedAmount = "1"; // 默认数量为1
				} else {
					data.setCopies(cachedAmount);
				}
				cartInfo = new ShopCartInfo(
						data.getRestaurantId(), data.getId(),
						data.getMenuName(), data.getPrice(), cachedAmount); 
				showBuf.append(cartInfo.toString()).append("@");
				
				ls = new ArrayList <ItemBase>();
				ls.add(data);
				String json = Utils.makeJson(ls, "3");
				realBuf.append(json).append("@");
			}
			// delete the last '&'.
			if (showBuf.length() > 0 && showBuf.charAt(showBuf.length() - 1) == '&') {
				showBuf.deleteCharAt(showBuf.length() - 1);
			}
			if (realBuf.length() > 0 && realBuf.charAt(realBuf.length() - 1) == '&') {
				realBuf.deleteCharAt(realBuf.length() - 1);
			}
			showStr = showBuf.toString();
			realStr = realBuf.toString();
		}

		// 获取显示item的数据
    	showDatas.clear();
        if (!TextUtils.isEmpty(showStr)) {
            String[] options = showStr.split("@");
            int size = options.length;
            for (int i = 0; i < size; i++) {
            	String[] option = options[i].split("&");
            	String restaurantId = option[0].substring(option[0].indexOf("=") + 1);
        		String productId = option[1].substring(option[1].indexOf("=") + 1);
        		String productName = option[2].substring(option[2].indexOf("=") + 1);
        		String productPrice = option[3].substring(option[3].indexOf("=") + 1);
        		String productAmount = option[4].substring(option[4].indexOf("=") + 1);
        		ShopCartInfo info = new ShopCartInfo(restaurantId, productId, productName, productPrice, productAmount);
        		sum_ += Float.parseFloat(productPrice) * Integer.parseInt(productAmount);
        		sum_ = (float) Math.round(sum_ * 10) / 10;
        		showDatas.add(info);
            }
        }
        
        // 获取item实际数据
        if (!TextUtils.isEmpty(realStr)) {
            String[] joptions = realStr.split("@");
            int jsize = joptions.length;
            for (int j = 0; j < jsize; j++) {
            	List itemLs = Utils.parseJson(joptions[j], "3");
            	ItemMeal ib = (ItemMeal) itemLs.get(0);
            	String copies = ib.getCopies();
            	if (copies == null || copies.trim().equals("")) {
					ib.setCopies("1");
				}
            	realDatas.add(ib);
            }
        }
    }

	/**
	 * 触摸事件中断处理
	 */
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// 当手指触到listview的时候，让父ScrollView交出ontouch权限，也就是让父scrollview停住不能滚动
			setParentScrollAble(false);
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			// 当手指松开时，让父ScrollView重新拿到onTouch权限
			setParentScrollAble(true);
			break;
		default:
			break;
		}
		return super.onInterceptTouchEvent(ev);
	}
	

	/**
	 * 是否把滚动事件交给父scrollview
	 * 
	 * @param flag
	 */
	private void setParentScrollAble(boolean flag) {
		// 这里的getParent()就是listview外面的那个父ScrollView
		this.getParent().requestDisallowInterceptTouchEvent(!flag);
	}
	
    public class ListAdapter extends BaseAdapter {
        private Activity mActivity = null;

        public ListAdapter(Activity activity) {
        	mActivity = activity;
        }

        @Override
        public int getCount() {
            return showDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return showDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                // 下拉项布局
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.shopcart_local_list_item, null);
                holder.name = (TextView) convertView.findViewById(R.id.shop_cart_local_item_name);
                holder.price = (TextView) convertView.findViewById(R.id.shop_cart_local_item_price);
                holder.minus = (Button) convertView.findViewById(R.id.shop_cart_local_item_minus);
                holder.amount = (TextView) convertView.findViewById(R.id.shop_cart_local_item_amount);
                holder.plus = (Button) convertView.findViewById(R.id.shop_cart_local_item_plus);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            
            holder.name.setText(showDatas.get(position).getProductName());
            holder.price.setText(showDatas.get(position).getProductPrice() + "元/份");
            holder.amount.setText("X " + showDatas.get(position).getProductAmount() + " 份");
            holder.minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                	int mInt = Integer.parseInt(showDatas.get(position).getProductAmount());
                	// 不允许出现0份
                	if (mInt > 1) {
                		// 联动份数
                		mInt--;
                		amountList.put(showDatas.get(position).getProductId(), String.valueOf(mInt));
                		showDatas.get(position).setProductAmount(String.valueOf(mInt));
                		((ItemMeal)realDatas.get(position)).setCopies(String.valueOf(mInt));
                		holder.amount.setText("X " + mInt + " 份");
                		
                		// 联动总价
                    	float decs = Float.parseFloat(showDatas.get(position).getProductPrice());
                    	sum_ -= decs;
                    	if (sum_ > 0) {
                    		sum_ = (float) Math.round(sum_ * 10) / 10;
                    	} else {
                    		// 不允许出现负价
                    		sum_ = 0;
                    	}
    					totalView_.setText("合计：¥ " + sum_ + " 元");
    					// 保存到本地
    					updateCache(showDatas.get(position).getRestaurantId(), showDatas.get(position).getProductId(), "minus");
    					
    					// 通知listView刷新
    			        notifyDataSetChanged();
					} else if (mInt == 1) {
						// 在listview删除一条纪录
						deleteItem(bv_, (ListAdapter) listView_.getAdapter(), position);
					}
                }
            });
            
            holder.plus.setOnClickListener(new View.OnClickListener() {
            	@Override
            	public void onClick(View v) {
                	// 联动份数
                	int mInt = Integer.parseInt(showDatas.get(position).getProductAmount());
                	mInt++;
                	amountList.put(showDatas.get(position).getProductId(), String.valueOf(mInt));
                	showDatas.get(position).setProductAmount(String.valueOf(mInt));
                	((ItemMeal)realDatas.get(position)).setCopies(String.valueOf(mInt));
                	holder.amount.setText("X " + mInt + " 份");

                	// 联动总价
                	float decs = Float.parseFloat(showDatas.get(position).getProductPrice());
                	sum_ += decs;
                	if (sum_ > 0) {
                		sum_ = (float) Math.round(sum_ * 10) / 10;
                	} else {
                		// 不允许出现负价
                		sum_ = 0;
                	}
					totalView_.setText("合计：¥ " + sum_ + " 元");

					// 保存到本地
					updateCache(showDatas.get(position).getRestaurantId(), showDatas.get(position).getProductId(), "plus");
                }
            });

            return convertView;
        }
    }

    class ViewHolder {
        TextView name;
        TextView price;
        Button minus;
        TextView amount;
        Button plus;
    }
    
	/**
	 * 删除菜品提示
	 * 
	 * @param activity
	 */
    public void deleteItem(final BaseView activity, final ShopCartList.ListAdapter adapter, final int position) {
    	String info = "您要删除该菜品吗？";
    	final Dialog doubleAlert_ = Alert.createDoubleAlert (activity, "提  示", info, "确定", "取消");
        doubleAlert_.setCancelable(true);
        ((Button) doubleAlert_.findViewById(R.id.btn_positive)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
        		// 联动总价
            	float decs = Float.parseFloat(showDatas.get(position).getProductPrice());
            	sum_ -= decs;
            	if (sum_ > 0) {
            		sum_ = (float) Math.round(sum_ * 10) / 10;
            	} else {
            		// 不允许出现负价
            		sum_ = 0;
            	}
				totalView_.setText("合计：¥ " + sum_ + " 元");
				
				doubleAlert_.dismiss();
				// 清除对应缓存
				ItemBase itdata = realDatas.get(position);
				String key = itdata.getId();
				ShopCart.order.remove(key);
				amountList.remove(key);
                // 删除某个item
            	showDatas.remove(position);
            	realDatas.remove(position);
            	attrValue_ = toJsonString(realDatas);
            	BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, attrValue_);
            	
            	// 刷新adapter
            	adapter.notifyDataSetChanged();
        		
				if (showDatas.size() == 0) {
					attrValue_ = "";
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    // 设置选中索引
                    data.putBoolean("isEmpty", true);
                    msg.setData(data);
                    msg.what = 1;
                    // 发出消息
                    handler.sendMessage(msg);
				}
				
				BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, attrValue_);
            }
        });

        ((Button) doubleAlert_.findViewById(R.id.btn_negative)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                doubleAlert_.dismiss();
            }
        });
        if (!activity.isFinishing() && !doubleAlert_.isShowing()) {
                doubleAlert_.show();
        }
    }
    
    /**
     * 当加减份数，更新缓存
     * @param restaurantId
     * @param productId
     * @param type
     */
    private void updateCache(String restaurantId, String productId, String type) {
        int size = showDatas.size();
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < size; i++) {
        	String rid = showDatas.get(i).getRestaurantId();
        	String pid = showDatas.get(i).getProductId();
        	// 查找匹配
        	if (restaurantId.equalsIgnoreCase(rid) && productId.equalsIgnoreCase(pid)) {
        		int amount = Integer.parseInt(showDatas.get(i).getProductAmount());
        		if ("plus".equalsIgnoreCase(type)) {
        			// 加1
        			showDatas.get(i).setProductAmount(String.valueOf(amount++));
        		} else if ("minus".equalsIgnoreCase(type)) {
        			// 减1
        			showDatas.get(i).setProductAmount(String.valueOf(amount--));
        		}
        	}
        	buf.append(showDatas.get(i).toString());
        	buf.append("@");
        }
		// delete the last '&'.
		if (buf.length() > 0 && buf.charAt(buf.length() - 1) == '@') {
			buf.deleteCharAt(buf.length() - 1);
		}
		attrValue_ = toJsonString(realDatas);
		BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_DB, buf.toString());
		BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, attrValue_);
    }
    
	public String toJsonString(List<ItemBase> ls) {
		String mJson = null;
		GsonBuilder gsonBuilder = new GsonBuilder();
		Gson gson = gsonBuilder.create();
		Type type = new TypeToken<List<ItemMeal>>(){}.getType();
		mJson = gson.toJson(ls, type);
		return  mJson;
	}
	
	@Override
	public String getContentText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setContentText(String text) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void shrinkWidth() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void cleanText() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mould() {
		CssStyle cs = cssStyle_;
		if (cs != null ) {
			if (cs.width_ != 0) {
				width_ = cs.width_;
			} else {
				width_ = Utils.screenWidth_ * 9 / 10;
			}
			if (cs.height_ != 0) {
				height_ = cs.height_;
			} else {
				caculateHeight();
			}
		} else {
			width_ = Utils.screenWidth_ * 9 / 10;
			// 根据内容大小设置控件高度
			caculateHeight();
		}
	}

	@Override
	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int getCmpWidth() {
		// TODO Auto-generated method stub
		return width_;
	}

	@Override
	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int getCmpHeight() {
		// TODO Auto-generated method stub
		return height_;
	}

	@Override
	public void setCssStyle(CssStyle style) {
		cssStyle_ = style;
	}

	@Override
	public View getCmpView() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public void setInTable(boolean inTable) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isInTable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public CssStyle getCssStyle() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void releaseResource(View view) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setForm(FormLayout formLayout) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub
		
	}

}
